package mapkit.layers
{
	import mapkit.MapEvent;

	public class TileImageLayer extends ImageLayer
	{
		private var _def:TileDefinition=new WMSTileDefinition();

		public function get definition():TileDefinition
		{
			return _def;
		}

		public function set definition(value:TileDefinition):void
		{
			_def=value;
		}

		private var _buffer:Object=new Object();

		protected function bufferGet(tile:TileInfo):MapImage
		{
			var key:String=tile.toString();
			if (_buffer[key] && contains(_buffer[key]))
			{
				return _buffer[key];
			}
			return null;
		}

		protected function bufferAdd(tile:TileInfo):MapImage
		{
			var key:String=tile.toString();

			if (!_buffer[key])
			{
				_buffer[key]=new imageClass();
			}

			if (!contains(_buffer[key]))
			{
				addChild(_buffer[key]);
			}

			return _buffer[key];
		}

		protected function bufferRemove(tile:TileInfo):void
		{
			var key:String=tile.toString();

			if (_buffer[key])
			{
				if (contains(_buffer[key]))
				{
					removeChild(_buffer[key]);
				}
				delete _buffer[key];
			}
		}

		private var _tileGrid:TileGrid=null;
		private var _lastTileGrid:TileGrid=null;
		private var _image:MapImage=null;

		override protected function updateMap(event:MapEvent=null):void
		{
			super.updateMap(event);

			if (_tileGrid)
			{
				_lastTileGrid=_tileGrid.clone();
			}

			_tileGrid=definition.getTileExtent(map);

			var tiles:Array=_tileGrid.getTileInfos(_lastTileGrid);
			for each (var tile:TileInfo in tiles)
			{
				switch (tile.operator)
				{
					case TileInfo.ADD:
						_image=bufferAdd(tile);
						_image.extent=definition.getExtent(tile);
						_image.url=baseURL;
						_image.width=definition.tileWidth;
						_image.height=definition.tileHeight;
						_image.x=(tile.col - _tileGrid.minCol) * definition.tileWidth +
							_tileGrid.offsetX;
						_image.y=(tile.row - _tileGrid.minRow) * definition.tileHeight +
							_tileGrid.offsetY;
						break;
					case TileInfo.IGNORE:
						_image=bufferGet(tile);
						_image.x=(tile.col - _tileGrid.minCol) * definition.tileWidth +
							_tileGrid.offsetX;
						_image.y=(tile.row - _tileGrid.minRow) * definition.tileHeight +
							_tileGrid.offsetY;
						break;
					case TileInfo.REMOVE:
						bufferRemove(tile);
						_image=null;
						break;
				}
			}
		}
	}
}